/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.admin.modules.sys.controller;

import com.chengcang.admin.common.annotation.LogOperation;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.admin.modules.sys.dto.SysMenuDTO;
import com.chengcang.admin.modules.sys.dto.SysRoleDTO;
import com.chengcang.admin.modules.sys.dto.SysRoleUserDTO;
import com.chengcang.admin.modules.sys.dto.SysRoleUserUnbindDTO;
import com.chengcang.admin.modules.sys.service.*;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.page.PageData;
import com.chengcang.common.utils.Result;
import com.chengcang.common.validator.AssertUtils;
import com.chengcang.common.validator.ValidatorUtils;
import com.chengcang.common.validator.group.AddGroup;
import com.chengcang.common.validator.group.DefaultGroup;
import com.chengcang.common.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

/**
 * 角色管理
 *
 * @author zhanli
 */
@RestController
@RequestMapping("/sys/role")
@Api(tags = "角色管理")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleUserService sysRoleUserService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysRoleDataScopeService sysRoleDataScopeService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "name", value = "角色名", paramType = "query", dataType = "String")
    })
    @RequiresPermissions("sys:role:page")
    public Result<PageData<SysRoleDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysRoleDTO> page = sysRoleService.page(params);

        return new Result<PageData<SysRoleDTO>>().ok(page);
    }

    @GetMapping("list")
    @ApiOperation("列表")
    @RequiresPermissions("sys:role:list")
    public Result<List<SysRoleDTO>> list() {
        List<SysRoleDTO> data = sysRoleService.list(new HashMap<>(1));

        return new Result<List<SysRoleDTO>>().ok(data);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sys:role:info")
    public Result<SysRoleDTO> get(@PathVariable("id") Long id) {
        SysRoleDTO data = sysRoleService.get(id);
        Optional.ofNullable(data).orElseThrow(() -> new CustomException("未查询到该角色！"));
        //查询角色对应的菜单
        List<Long> menuIdList = sysRoleMenuService.getMenuIdList(id);
        data.setMenuIdList(menuIdList);
        Long tenantId = SecurityUser.getTenantId();
        List<SysMenuDTO> allMenuList;
        if (null != tenantId && 1L != tenantId) {
            allMenuList = sysMenuService.getUserMenuList(SecurityUser.getUser(), null);
        } else {
            allMenuList = sysMenuService.getAllMenuList(null);
        }
        statusComplement(allMenuList, menuIdList);
        data.setMenuList(allMenuList);
        //查询角色对应的数据权限
        List<Long> deptIdList = sysRoleDataScopeService.getDeptIdList(id);
        data.setDeptIdList(deptIdList);

        return new Result<SysRoleDTO>().ok(data);
    }

    private void statusComplement(List<SysMenuDTO> allMenuList, List<Long> menuIdList) {
        for (SysMenuDTO sysMenuDTO : allMenuList) {
            sysMenuDTO.setStatus(menuIdList.contains(sysMenuDTO.getId()));
            if (CollectionUtils.isNotEmpty(allMenuList)) {
                statusComplement(sysMenuDTO.getChildren(), menuIdList);
            }
        }
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sys:role:save")
    public Result save(@RequestBody SysRoleDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysRoleService.save(dto);

        return new Result();
    }

    @PostMapping("copy")
    @ApiOperation("复制")
    @LogOperation("复制")
    @RequiresPermissions("sys:role:copy")
    public Result copy(@RequestBody SysRoleDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysRoleService.copy(dto);

        return new Result();
    }

    @PostMapping("saveRoleUser")
    @ApiOperation("添加人员")
    @LogOperation("添加人员")
    @RequiresPermissions("sys:roleUser:save")
    public Result saveRoleUser(@RequestBody SysRoleUserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        for (Long userId : dto.getUserIds()) {
            sysRoleUserService.saveOrUpdate(userId, Arrays.asList(dto.getRoleId()));
        }

        return new Result();
    }

    @PostMapping("unbindRoleUser")
    @ApiOperation("解绑角色和人员")
    @LogOperation("解绑角色和人员")
    @RequiresPermissions("sys:roleUser:delete")
    public Result unbindRoleUser(@RequestBody SysRoleUserUnbindDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, DefaultGroup.class);
        sysRoleUserService.deleteByRoleIdAndUserIds(dto.getRoleId(), dto.getUserId());

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sys:role:update")
    public Result update(@RequestBody SysRoleDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysRoleService.update(dto);

        return new Result();
    }

    @GetMapping("updateStatus")
    @ApiOperation("修改状态")
    @LogOperation("修改状态")
    @RequiresPermissions("sys:role:updateStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "id", value = "客户id"),
            @ApiImplicitParam(required = true, name = "status", value = "0 正常 1 禁用"),
            @ApiImplicitParam(required = false, name = "remark", value = "备注")
    })
    public Result updateStatus(@RequestParam Long id, @RequestParam Integer status,
                               @RequestParam(required = false) String remark) {
        SysRoleDTO sysDeptDTO = new SysRoleDTO();
        sysDeptDTO.setId(id);
        sysDeptDTO.setStatus(status);
        sysDeptDTO.setRemark(remark);
        sysRoleService.update(sysDeptDTO);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:role:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        sysRoleService.delete(ids);

        return new Result();
    }
}